<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head th:include="public/include::headerBasic(操作主界面,~{::style})">
    <style>

    </style>
</head>
<body>

<div style="display: flex;justify-content: center;flex-direction: column;align-items: center">
    <div class="layui-form-item" style="margin-top: 15px">
        <label class="layui-form-label">添加主题</label>
        <div class="layui-input-inline">
            <input type="text" id="sTopic" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
        <button class="layui-btn" id="subscribeTopic">提交</button>
    </div>

    <div class="layui-form-item" style="margin-top: 15px">
        <label class="layui-form-label">删除主题</label>
        <div class="layui-input-inline">
            <input type="text" id="dTopic" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
        <button class="layui-btn" id="removeTopic">提交</button>
    </div>

    <form class="layui-form">
        <div class="layui-form-item" style="margin-top: 15px;display: flex;">
            <label class="layui-form-label">测试推送</label>
            <div id="demo1" class="xm-select-demo" style="width: 200px"></div>
            <label class="layui-form-label">推送内容</label>
            <div class="layui-input-inline" style="margin-left: 15px">
                <input type="text" id="payload" required lay-verify="required" autocomplete="off" class="layui-input">
            </div>
            <input style="margin-left: 15px" type="button" class="layui-btn" value="更新订阅主题" id="updateTopics">
            <input type="button" class="layui-btn" value="推送" id="pushMsg">
        </div>
    </form>
    <!--前端订阅到的数据-->
    <div class="layui-form-item" style="margin-top: 15px">
        <label class="layui-form-label" style="width: 150px">JS端默认订阅：testtopic/#</label>
    </div>
    <div class="layui-form-item" style="margin-top: 15px">
        <label class="layui-form-label">消息的主题</label>
        <div class="layui-input-inline">
            <input type="text" id="sTopicTitle" readonly autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label">消息的内容</label>
        <div class="layui-input-inline">
            <input type="text" id="sTopicContent" readonly autocomplete="off" class="layui-input">
        </div>
    </div>
</div>
<th:block th:include="public/include :: footer"/>
<script>

    let demo1;


    /**
     * 订阅主题的操作
     */
    $("#subscribeTopic").on("click", function () {
        let topic = $("#sTopic").val();
        $.ajax({
            url: 'add',
            data: {
                topic: topic
            },
            dataType: 'json',
            success: function (data) {
                layer.msg(data)
            }
        })
    });


    /**
     * 删除主题的操作
     */
    $("#removeTopic").on("click", function () {
        let topic = $("#dTopic").val();
        $.ajax({
            url: 'remove',
            data: {
                topic: topic
            },
            dataType: 'json',
            success: function (data) {
                layer.msg(data);
            }
        })
    });


    /**
     * 更新主题的操作
     */
    $("#updateTopics").on("click", function () {
        updateTopic();
    });

    function updateTopic(){
        $.ajax({
            url: 'getAll',
            dataType: 'json',
            success: function (data) {
                demo1 = xmSelect.render({
                    el: '#demo1',
                    tips: '请选择主题?',
                    radio: true,
                    clickClose: true,
                    model: {icon: 'hidden', label: {type: 'text'}},
                    prop: {
                        name: 'name',
                        value: 'value'
                    },
                    data: data
                });
                demo1.setValue(data[0].value)
            }
        })
    }


    /**
     * 推送消息
     */
    $("#pushMsg").on("click", function () {
        //先获取到主题
        let selectArr = demo1.getValue('name');
        //再获取到要推送的内容
        let payload = $("#payload").val();
        $.ajax({
            url: 'push',
            dataType: 'json',
            data: {
                topic: selectArr[0],
                payload: payload
            },
            success: function (data) {
                layer.msg(data);
            }
        })
    });

    $(function () {
        updateTopic();
        const options = {
            clean: true,
            connectTimeout: 4000,
            clientId: 'emqx_client_h5',
            username: "t_user",
            password: 'njcnpqs'
        }
        const connectUrl = 'ws://192.168.1.14:8083/mqtt'
        const client = mqtt.connect(connectUrl, options);

        //当重新连接启动触发回调
        client.on('reconnect', () => {
            $("#div1").text("正在重连.....");
        });
        //连接断开后触发的回调
        client.on("close", function () {
            $("#div1").text("客户端已断开连接.....");
        });
        //从broker接收到断开连接的数据包后发出。MQTT 5.0特性
        client.on("disconnect", function (packet) {
            $("#div1").text("从broker接收到断开连接的数据包....." + packet);
        });
        //客户端脱机下线触发回调
        client.on("offline", function () {
            $("#div1").text("客户端脱机下线.....");
        });
        //当客户端无法连接或出现错误时触发回调
        client.on("error", (error) => {
            $("#div1").text("客户端出现错误....." + error);
        });
        //当客户端发送任何数据包时发出。这包括published()包以及MQTT用于管理订阅和连接的包
        client.on("packetsend", (packet) => {
            $("#div1").text("客户端已发出数据包....." + packet);
        });
        //当客户端接收到任何数据包时发出。这包括来自订阅主题的信息包以及MQTT用于管理订阅和连接的信息包
        client.on("packetreceive", (packet) => {
            $("#div1").text("客户端已收到数据包....." + packet);
        });

        //成功连接后触发的回调
        // client.on("connect",function (connack) {
        //     $("#div1").text("成功连接上服务器"+new Date());
        //     //订阅某主题
        //     /**
        //      * client.subscribe(topic/topic array/topic object, [options], [callback])
        //      * topic:一个string类型的topic或者一个topic数组,也可以是一个对象
        //      * options
        //      */
        //     client.subscribe("testtopic/#",{qos:2});
        //     //每隔2秒发布一次数据
        //     setInterval(publish,2000)
        // });

        // function publish() {
        //     //发布数据
        //     /**
        //      * client.publish(topic,message,[options], [callback])
        //      *
        //      * message: Buffer or String
        //      * options:{
        //      * qos:0, //默认0
        //      * retain:false, //默认false
        //      * dup:false, //默认false
        //      * properties:{}
        //      * }
        //      * callback:function (err){}
        //      */
        //     const message = "h5 message "+Math.random()+new Date();
        //     client.publish("testtopic/123",message,{qos:2});
        //     $("#div2").text("客户端发布了数据:"+message);
        // }

        //当客户端接收到发布消息时触发回调
        /**
         * topic:收到的数据包的topic
         * message:收到的数据包的负载playload
         * packet:收到的数据包
         */
        client.subscribe("testtopic/#", {qos: 2});
        client.on('message', (topic, message, packet) => {
            $("#sTopicTitle").val(topic)
            $("#sTopicContent").val(message)
        });
        //页面离开自动断开连接
        // $(window).bind("beforeunload",()=>{
        //     $("#div1").text("客户端窗口关闭,断开连接");
        //     client.disconnect();
        // })
    })
</script>
</body>
</html>